<template>
  <div class="w-full h-full bg-Center overflow-hidden">
    <WindowTab obj="previewImage">
      <div class="flex gap-2 items-center cursor-pointer [-webkit-app-region:no-drag]">
        <el-divider direction="vertical" />
        <i class="iconfont icon-fangda py-1.5 cursor-pointer" @click="zoomIn"></i>
        <i class="iconfont icon-suoxiao py-1.5 cursor-pointer" @click="zoomOut"></i>
        <el-divider direction="vertical" />
        <i class="iconfont icon-zuoxuanzhuan py-1.5 cursor-pointer" @click="rotateLeft" style="font-size: 18px"></i>
        <i class="iconfont icon-youxuanzhuan py-1.5 cursor-pointer" @click="rotateRight" style="font-size: 18px"></i>
        <el-divider direction="vertical" />
        <i class="iconfont icon-xiazai py-1.5 cursor-pointer" @click="download(PreviewList[cruuentIndex])"></i>
        <i class="iconfont icon-gengduo1 py-1.5 cursor-pointer"></i>
        <el-divider direction="vertical" />
      </div>
    </WindowTab>

    <!-- 内容区域 -->
    <div
      ref="scrollbar"
      style="border-top: 1px solid var(--border); height: calc(100vh - 47px); overflow: auto"
      @wheel.prevent="handleWheel"
    >
      <div class="preview-wrapper" :style="wrapperStyle">
        <n-image
          ref="imageEl"
          :src="PreviewList[cruuentIndex].url"
          :style="imageStyle"
          preview-disabled
          lazy
          class="preview-image"
          @mousedown="startDrag"
        >
          <template #error>
            <n-icon :size="100" color="lightGrey">
              <ImageOutlineIcon />
            </n-icon>
          </template>
        </n-image>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { ImageOutline as ImageOutlineIcon } from "@vicons/ionicons5";
import { NIcon, NImage } from "naive-ui";
import WindowTab from "@/components/WindowTab/index.vue";
import { IPreviewParams } from "@/types/previewImage";
import { Debounce } from "@/utils/common";

// 数据状态
let PreviewList = ref<IPreviewParams[]>([]);
const route = useRoute();
const query = route.query as unknown as IPreviewParams;
const cruuentIndex = ref(0);

// 图片变换状态
const scale = ref(1);
const rotateAngle = ref(0);

// DOM 引用
const scrollbar = ref<any>(null);
const imageEl = ref<HTMLElement | null>(null);

// 拖拽状态
const isDragging = ref(false);
const startPos = ref({ x: 0, y: 0, scrollLeft: 0, scrollTop: 0 });

// 计算样式
const imageStyle = computed(() => ({
  transform: `scale(${scale.value}) rotate(${rotateAngle.value}deg)`,
  transition: "transform 0.3s ease",
  cursor: isDragging.value ? "grabbing" : "grab",
}));

const wrapperStyle = computed(() => ({
  width: "100%",
  height: "100%",
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
  padding: "20px",
}));

// 拖拽功能
function startDrag(e: MouseEvent) {
  if (!scrollbar.value || !imageEl.value) return;
  console.log(scrollbar.value);

  isDragging.value = true;
  startPos.value = {
    x: e.clientX,
    y: e.clientY,
    scrollLeft: scrollbar.value.scrollLeft,
    scrollTop: scrollbar.value.scrollTop,
  };

  document.addEventListener("mousemove", dragImage);
  document.addEventListener("mouseup", endDrag);
  document.addEventListener("mouseleave", endDrag);
  e.preventDefault();
}

function dragImage(e: MouseEvent) {
  e.preventDefault();
  if (!isDragging.value || !scrollbar.value) return;
  const dx = e.clientX - startPos.value.x;
  const dy = e.clientY - startPos.value.y;
  scrollbar.value.scrollLeft = startPos.value.scrollLeft - dx;
  scrollbar.value.scrollTop = startPos.value.scrollTop - dy;
}

function endDrag() {
  isDragging.value = false;
  removeDragListeners();
}

function removeDragListeners() {
  document.removeEventListener("mousemove", dragImage);
  document.removeEventListener("mouseup", endDrag);
  document.removeEventListener("mouseleave", endDrag);
}

// 图片变换功能
function zoomIn() {
  scale.value = Math.min(scale.value + 0.1, 3);
  centerImage();
}

function zoomOut() {
  scale.value = Math.max(scale.value - 0.1, 0.2);
  centerImage();
}

const handleWheel = Debounce((e: WheelEvent) => {
  // 上滚 缩小
  if (e.deltaY >= 0) zoomIn();
  // 下滚 放大
  else zoomOut();
}, 200);

function rotateLeft() {
  rotateAngle.value = (rotateAngle.value - 90 + 360) % 360;
  centerImage();
}

function rotateRight() {
  rotateAngle.value = (rotateAngle.value + 90) % 360;
  centerImage();
}

function centerImage() {
  nextTick(() => {
    if (scrollbar.value?.containerRef) {
      const container = scrollbar.value.containerRef;
      container.scrollTo({
        left: (container.scrollWidth - container.clientWidth) / 2,
        top: (container.scrollHeight - container.clientHeight) / 2,
        behavior: "smooth",
      });
    }
  });
}

// 下载功能
function download(params: IPreviewParams) {
  const parts = params.name.split(".");
  const fileName = parts.slice(0, -1).join(".");
  const fileType = parts[parts.length - 1];
  window.electronApi.fileSave({
    fileName,
    fileType,
    url: params.url,
  });
}

// 监听路由参数
watch(
  () => query,
  (newQuery) => {
    if (newQuery.url) {
      PreviewList.value = [newQuery];
    }
  },
  { immediate: true },
);
</script>

<style lang="scss" scoped>
.preview-wrapper {
  min-width: 100%;
  min-height: 100%;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;

  &:hover {
    cursor: grab;
  }

  &:active {
    cursor: grabbing;
  }
}

:deep(.n-scrollbar-content) {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
